package com.guava.framework;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import org.nutz.dao.Dao;
import org.nutz.dao.impl.NutDao;

import com.alibaba.druid.pool.DruidDataSource;

import config.GHelper;
import config.FreemarkerHelp;
import config.SingletonDruidDataSource;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
public class Controller {
	private Dao dao =null;
	Map root = new HashMap();
	public Controller() {
		
	}

	public void setAttr(String s, Object o) {
		root.put(s, o);
	}
	public Dao getDao() {
		if(dao!=null){
			return dao;
		}
		  dao = new NutDao(SingletonDruidDataSource.getInstance());
		  return dao;
	}
	public void setSessionAttr(String key, Object value) {
		GHelper.request.getSession().setAttribute(key, value);
	}
	public Object getSessionAttr(String key) {
		return GHelper.request.getSession().getAttribute(key);
	}
	public String getPara(String pa) {
		return GHelper.request.getParameter(pa);
	}

	public int getParaToInt(String pa) {
		String v = GHelper.request.getParameter(pa);
		return Integer.parseInt(v);
	}

	public void renderText(String string) throws IOException {
		GHelper.response.getWriter().println(string);
	}

	public void render(String s) throws IOException {
		Router r = GHelper.r;
		// System.out.println(r.getController()+"-"+r.getAction()+".html");
		Configuration ctg = new Configuration();
		ctg.setServletContextForTemplateLoading(FreemarkerHelp.servletContext, "/");
		ctg.setTemplateUpdateDelay(0);
		// ctg.clearTemplateCache();
		Template t = null;
		if (s == "no") {
			t = ctg.getTemplate("index/" + r.getController() + "-" + r.getAction() + ".html");
			// t=GetSomething.getFreemarker().getTemplate("index/"+r.getController()
			// + "-" + r.getAction() + ".html");
		} else {
			// t=GetSomething.getFreemarker().getTemplate("index/"+s);
			t = ctg.getTemplate("index/" + s);
		}

		PrintWriter out = GHelper.response.getWriter();
		try {
			t.process(root, out);
		} catch (TemplateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (out != null) {
				out.close();
			}

		}
	}
}
